var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

//解决跨域
const cors = require('cors');
// const Result = require('./utils/api');

var indexRouter = require('./routes/index');

//后端路由导入
var apiArticle = require('./routes/adminApi/article');
var apiComment = require('./routes/adminApi/comment')
var apiLink = require('./routes/adminApi/link')
var apiUpload = require('./routes/adminApi/upload')
var apiUser = require('./routes/adminApi/user');

// 前端路由导入
var apiViewArticle = require('./routes/view/article')
var apiViewComment = require('./routes/view/comment')
var apiConfig = require('./routes/view/config');

var app = express();

// 配置静态资源目录 整一个文件夹 通过域名能访问

app.use(cors())
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
  extended: false
}));
app.use(cookieParser());

// 设置静态目录
app.use(express.static(path.join(__dirname, 'public')));

// 后端路由
app.use('/', indexRouter);
app.use('/api/v1', apiArticle);
app.use('/api/v1', apiComment)
app.use('/api/v1', apiLink)
app.use('/api/v1/upload', apiUpload)
app.use('/api/v1', apiUser)

// 前端路由
app.use('/api/v1', apiViewArticle)
app.use('/api/v1', apiViewComment)
app.use('/api/v1', apiConfig);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;